import React, { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
//图灵
import SliderCaptcha from 'rc-slider-captcha';
import { getCaptcha, verifyCaptcha } from './service1';
import { Form, Button, Input, TextArea } from '@nutui/nutui-react'
import { Tips } from '@nutui/icons-react'
import { userLogin, register, sendVerification } from "../../interfaces";
export default function Login() {
    const [form] = Form.useForm()//[数组嵌套对象] 获取表单实例
    const Navigate = useNavigate();
    const verifyState = useRef(false);//图灵验证码 显示隐藏开关
    const [islogin, setislogin] = useState(false)
    const verCode = useRef('')//验证码内容
    const [isFlag, setIsFlag] = useState(false);//登录注册开关
    const [verInput, setVarInput] = useState('')
    let [time, setTime] = useState(60)//验证码倒计时
    const [email, setEmail] = useState('')

    const onFinish = async ({ username, password }) => {
        // 通用接口封装
        // const res = await api.post('/login', { username: '李四', password: "654321" });
        // 接口单独封装
        if (!isFlag) {
            if (!verifyState.current) {
                alert('请完成图灵验证'); return
            }
            const res = await userLogin(username, password);
            if (res.data.code === 200) {
                verifyState.current = false;
                const { userInfo, accessToken, refreshToken } = res.data;
                localStorage.setItem('user', userInfo.usersname);
                localStorage.setItem('access_token', accessToken);
                localStorage.setItem('refresh_token', refreshToken);
                Navigate('/index/mine')
            }
        } else {
            if (!verInput) {
                alert('请输入验证码'); return
            } else if (verInput !== verCode.current) {
                alert('验证码输入不正确'); return
            } else {
                const res = await register(username, password);
                if (res.data.code === 200) {
                    alert('注册成功');
                }
            }
        }
    }
    const onFinishFailed = ({ username, password }, error) => {
        const forData = form.getFieldsValue(["username", "password"]);
        if (!forData.username || !forData.password) {
            alert('请正确完成账号或密码输入'); return
        }
        error.forEach(({ message }, index) => {
            alert((index ? password : username) + "：" + message); return
        })
    }
    let VerificationCode = async () => {
        const timer = setInterval(() => {
            setTime(time -= 1)
            if (time === 0) {
                setTime(60)
                clearInterval(timer)
            }
        }, 1000)
        const res = await sendVerification(form.getFieldValue('email'));
        if (res.data.code === 200) {
            console.log(res.data.verCode);
            verCode.current = res.data.verCode;
        }
    }
    let handoff = () => {
        setislogin(!islogin)
        setIsFlag(!isFlag)
    }
    return (
        <div style={{ display: 'flex', height: '100vh', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>


            <Form labelPosition="right" onFinish={onFinish} form={form} onFinishFailed={onFinishFailed}
                footer={
                    <>
                        <div style={{
                            width: '100%',
                        }}>
                            {/* 图灵验证码,request 异步返回背景图和滑块图。onVerify 用户滑动停止时触发，用于验证。
            参数 VerifyParam 一般情况下只需要用到拼图 x 轴偏移值。*/}
                            {isFlag ? (<div
                                style={{
                                    display: 'flex',
                                    alignItems: 'center',
                                    background: '#fff',
                                    padding: '0 10px',
                                }}
                            >
                                <Tips color="var(--nutui-gray-7)" />
                                <Input
                                    value={verInput}
                                    placeholder="请输入短信验证码"
                                    style={{ '--nutui-input-padding': '10px' }}
                                    onChange={(e) => setVarInput(e)}
                                />
                                <div className="right">
                                    <Button type="primary" size="small" onClick={VerificationCode} disabled={!email || time !== 60}>
                                        {time === 60 ? "获取验证码" : `${time}s后发送`}
                                    </Button>
                                </div>
                            </div>) : <SliderCaptcha
                                mode="float"
                                placement="top"
                                style={{ zIndex: 2 }}
                                request={getCaptcha}
                                onVerify={(data) => {
                                    verifyState.current = true;
                                    return verifyCaptcha(data);
                                }}
                            />}

                            <Button nativeType="submit" block type="primary" style={{ marginTop: "20px" }}>
                                {isFlag ? "注册" : "登录"}
                            </Button>
                            <div style={{ textAlign: "center", marginTop: "20px" }}>
                                <span onClick={handoff}>{isFlag ? "切换登录" : "切换注册"}</span>
                            </div>
                        </div>
                    </>
                }
            >

                <Form.Item style={{ display: 'flex', justifyContent: 'center' }}>
                    <h1>
                        {isFlag ? "注册页面" : "登录页面"}
                    </h1>
                </Form.Item>

                {islogin ? <Form.Item label="手机号/邮箱" name="email"
                    rules={[
                        { required: true, message: '手机号或邮箱不能为空' },
                    ]}
                >
                    <TextArea placeholder="请输入手机号/邮箱" maxLength={100} value={email} onInput={(e) => setEmail(e.target.value)} />
                </Form.Item> : ''}

                <Form.Item align="center" required label="账号" name="username"
                    rules={[
                        { required: true, message: '请输入账号名' },
                        { max: 8, message: '账号超过8个字符' },
                    ]}
                >
                    <Input className="nut-input-text" placeholder="请输入账号" type="text" />
                </Form.Item>
                <Form.Item label="密码" name="password"
                    rules={[
                        { min: 6, max: 12, message: '密码不满足6-12字符' },
                        { required: true, message: '密码不能为空' },
                    ]}
                >
                    <TextArea placeholder="请输入密码" maxLength={100} />
                </Form.Item>
            </Form>
        </div >
    )
}
